import {
  receivePageApi,
  addReceiveApi,
  editReceiveApi,
  delReceiveApi
} from '@/api/workflow/receive'
import { Ref } from 'vue'
import { ProTableInst } from '@/components/pro-table/type'
import { PageRequest } from '@/api/types'
import { ReceiveModel } from '@/api/model/workflow/receive-model'
import { userInfoModel } from '@/api/model/userModel'
import { userInfo } from '~/types/user'
import dayjs from 'dayjs'

type Props = {
  handleType: Ref<'add' | 'edit' | 'check'>
  handleTag: Ref<string>
  receiveModalShow: Ref<boolean>
  receiveForm: Ref<Partial<ReceiveModel>>
  proTableInst: Ref<ProTableInst | null>
  userInfo: Ref<userInfo<userInfoModel>>
}

export const useReceiveApi = ({
  handleType,
  handleTag,
  receiveModalShow,
  receiveForm,
  proTableInst,
  userInfo
}: Props) => {
  const confirmLoading = ref(false)

  // 获取领用列表
  const fetchReceivePage = async (
    pageRequest: PageRequest,
    queryParams: ReceiveModel
  ) => {
    const res = await receivePageApi({
      ...queryParams,
      orgId: userInfo.value.orgId,
      pageRequest
    })

    if (res.code === '0000') {
      return {
        data: res.data?.content,
        total: res.data?.total
      }
    }
  }

  // 新增or修改领用
  const fetchAddOrEditReceive = async () => {
    confirmLoading.value = true
    const fetch = handleType.value === 'add' ? addReceiveApi : editReceiveApi
    const data =
      handleType.value === 'add'
        ? {
            ...receiveForm.value,
            receivePerson: userInfo.value.userName,
            receivePersonId: userInfo.value.userId,
            getPerson: userInfo.value.userName,
            getPersonId: userInfo.value.userId,
            receiveBranch: userInfo.value.orgName,
            receiveBranchId: userInfo.value.orgId,
            getBranch: userInfo.value.orgName,
            getBranchId: userInfo.value.orgId,
            receiveDate: dayjs().format('YYYY-MM-DD'),
            typeId: receiveForm.value.typeId.toString()
          }
        : {
            ...receiveForm.value,
            typeId: receiveForm.value.typeId.toString()
          }
    if (data.__displayValue__) delete data.__displayValue__
    const res = await fetch(data)
    if (res.code === '0000') {
      useMsg('success', handleTag.value + '成功')
      proTableInst.value?.reload()
      receiveModalShow.value = false
    }
    confirmLoading.value = false
  }

  // 删除领用
  const fetchDelReceive = async (id) => {
    const res = await delReceiveApi({ id })
    if (res.code === '0000') {
      useMsg('success', '删除成功')
      proTableInst.value?.reload()
    }
  }

  return {
    fetchReceivePage,
    fetchAddOrEditReceive,
    fetchDelReceive,
    confirmLoading
  }
}
